package com.marketingexpert.service.marketingmgnt;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.ServletContext;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;
import org.springframework.web.context.ServletContextAware;

import com.marketingexpert.config.Configuration;
import com.marketingexpert.domain.Trend;
import com.marketingexpert.domain.TrendWeiboId;
import com.marketingexpert.domain.User;
import com.marketingexpert.domain.UserType;
import com.marketingexpert.exception.MarketingExpertException;
import com.marketingexpert.service.messagemgnt.MessageService;
import com.marketingexpert.service.messagemgnt.impl.MessageServiceImpl;
import com.marketingexpert.service.usermgnt.UserService;
import com.marketingexpert.util.Resources;

/**
 * 
 * 自动营销
 * @author Administrator
 * 
 */
public class AutoMarketingJob implements ServletContextAware {

	private static final int BUFFER = 1024;

	private static Logger logger = Logger.getLogger(AutoMarketingJob.class);

	private ServletContext servletContext;

	private UserService userService;

	private MessageService messageService;

	private MarketingService marketingService;

	private int time = 1;

	private Map<String, Object> marketingMaterial = null;

	private Configuration configuration;

	/**
	 * 查询淘宝用户,并给定制了自动营销功能的用户发微薄
	 */
	public void autoSendWeiboExecutor() {

		int pageCursor = 0;
		int userCount = getUserService().queryUserCount(UserType.TAOBAO);		
		int pageCount = 1;//用户的总页数(每页10个用户)
		if (userCount < 10) {
			pageCount = 1;
		} else if ((userCount % 10) == 0) {
			pageCount = userCount / 10;
		} else {
			pageCount = userCount / 10 + 1;
		}
		
		//分页查询用户
		for (int _i = 0; _i < pageCount; _i++) {
			pageCursor = _i * 10; //游标
			List<User> parentUsers = getUserService().queryAllUser(pageCursor,10, UserType.TAOBAO);
			int[] userIds = new int[parentUsers.size()];
			for (int i = 0; i < parentUsers.size(); i++) { //获取用户的id
				userIds[i] = parentUsers.get(i).getId();
			}
			List<Trend> trends = getMarketingService().queryAllTrendByUserId(userIds, time);//获取用户选择的自动营销类型(关键字)
			try {
				for (Trend trend : trends) {
					String meterialIdsStr = configuration.getMaterialId(trend.getTrend());
					if (meterialIdsStr == null || meterialIdsStr.equals("")) {
						continue;
					}					
					if (marketingMaterial == null) {
						marketingMaterial = getOneTrendMessage(meterialIdsStr);
					}
					
					for (TrendWeiboId twi : trend.getTrendsWeiboIds()) {
							User user = userService.queryUserByUId(twi.getWeiboUserId());
							if (user == null) {
								continue;
							}
							marketingService.autoMarketingExecute(marketingMaterial, user);
					}
					
					boolean isDelete = MessageServiceImpl.deleteImage((String) marketingMaterial.get("fileRealPath"));
					if (!isDelete) {
						logger.error("auto marekting delte image Failed,image name:"
										+ marketingMaterial.get("fileRealPath"));
					}
					marketingMaterial = null;
				}
			} catch (MarketingExpertException e) {
				logger.error(e.getMessage(), e);
				throw e;
			}

		}
	}

	/**
	 * 获取一条要发送的微博内容
	 * @param meterialIds 从微博中查询微博的所有人的微博id
	 * @return
	 */
	public Map<String, Object> getOneTrendMessage(String meterialIds) {
		try {
			Map<String, Object> materialWeibo = marketingService.getOneTrendMessage(meterialIds);
			File f = null;
			String fileRealPath = null;
			if (materialWeibo.get("picture") != null
					&& !materialWeibo.get("picture").equals("")) {
				try {
					URL url = new URL((String) materialWeibo.get("picture"));
					String fileName = url.getFile();
					fileRealPath = servletContext.getRealPath("/")
							+ "upload/image/automarketing/"
							+ fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
					logger.warn("�Զ�Ӫ���ȡͼƬ�洢·��: " + fileRealPath);
					HttpClient client = new HttpClient();  
			        GetMethod get = new GetMethod((String) materialWeibo.get("picture"));  
			        client.executeMethod(get);  
			        f = new File(fileRealPath);  
			        FileOutputStream output = new FileOutputStream(f);  
			        output.write(get.getResponseBody());  
			        output.close();  
				} catch (MalformedURLException e) {
					logger.error("AutoMarketingJob.constructImageUrlFailed", e);
					throw new MarketingExpertException(e);
				} catch (IOException e) {
					logger.error(Resources.getString("AutoMarketingJob.readImageFailed"), e);
					throw new MarketingExpertException(e);
				}

			}

			if (f != null) {
				materialWeibo.put("picture", f);
				materialWeibo.put("fileRealPath", fileRealPath);
			} else {
				materialWeibo.remove("picture");
			}
			return materialWeibo;
		} catch (MarketingExpertException e) {
			throw e;
		}
	}
	
	/*public Map<String, Object> getOneTrendMessage(String uid) {
		try {
			Map<String, Object> materialWeibo = marketingService.getOneTrendMessage(uid);
			File f = null;
			String fileRealPath = null;
			if (materialWeibo.get("picture") != null
					&& !materialWeibo.get("picture").equals("")) {
				try {
					URL url = new URL((String) materialWeibo.get("picture"));
					String fileName = url.getFile();
					fileRealPath = servletContext.getRealPath("/")
							+ "upload/image/automarketing/"
							+ fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
					logger.warn("�Զ�Ӫ���ȡͼƬ�洢·��: " + fileRealPath);
					HttpClient client = new HttpClient();  
			        GetMethod get = new GetMethod((String) materialWeibo.get("picture"));  
			        client.executeMethod(get);  
			        f = new File(fileRealPath);  
			        FileOutputStream output = new FileOutputStream(f);  
			        output.write(get.getResponseBody());  
			        output.close();  
				} catch (MalformedURLException e) {
					logger.error("AutoMarketingJob.constructImageUrlFailed", e);
					throw new MarketingExpertException(e);
				} catch (IOException e) {
					logger.error(Resources.getString("AutoMarketingJob.readImageFailed"), e);
					throw new MarketingExpertException(e);
				}

			}

			if (f != null) {
				materialWeibo.put("picture", f);
				materialWeibo.put("fileRealPath", fileRealPath);
			} else {
				materialWeibo.remove("picture");
			}
			return materialWeibo;
		} catch (MarketingExpertException e) {
			throw e;
		}
	}*/

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public MessageService getMessageService() {
		return messageService;
	}

	public void setMessageService(MessageService messageService) {
		this.messageService = messageService;
	}

	public MarketingService getMarketingService() {
		return marketingService;
	}

	public void setMarketingService(MarketingService marketingService) {
		this.marketingService = marketingService;
	}

	public int getTime() {
		return time;
	}

	public void setTime(int time) {
		this.time = time;
	}

	public Configuration getConfiguration() {
		return configuration;
	}

	public void setConfiguration(Configuration configuration) {
		this.configuration = configuration;
	}

	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
		logger.debug("the server real path:" + servletContext.getRealPath("/"));
	}
}
